<template>
  <div class="personal-step" v-loading="loading">
    <personalStep ref="steps" :bussType="bussType" :id="stepId" :certType="certType" @loading="handleLoading" />
  </div>
</template>
<script>
import personalStep from './components/PersonalStep.vue';
import userApi from '@/api/user';
import businessApi from '@/api/business';
import { decrypt } from '@/utils/sms4util';

export default {
  props: {
    key: {
      type: String,
    },
    bussType: {
      default: '1',
    },
    certType: {
      default: '1',
    }
  },
  components: {
    personalStep,
  },
  created() {
    this.initData();
  },
  data() {
    return {
      userData: {},
      stepId: null,
      loading: false
    };
  },
  computed: {
    // 是否是注册
    isReg() {
      return (this.bussType == 1 && this.certType == '1') || (this.bussType == 'a' && this.certType == '3')
    },
    noCertCodes() {
      const { safeQua, regCert, mwrCerts } = this.userData;
      if (this.certType == '1') {
        return !regCert;
      } else {
        return (!safeQua && !mwrCerts)
            || ((safeQua && !safeQua.mainCertCode && !safeQua.projCertCode && !safeQua.classifyCertCode)
                && (mwrCerts && !mwrCerts.mainCertCode && !mwrCerts.projCertCode && !mwrCerts.classifyCertCode))
      }
    },
    hasAllCert() {
      const { safeQua, regCert, mwrCerts } = this.userData;
      if (this.certType == '1') {
        return regCert;
      } else {
        return ( (safeQua || mwrCerts)
            && (safeQua?.mainCertCode || mwrCerts?.mainCertCode)
            && (safeQua?.projCertCode || mwrCerts?.projCertCode)
            && (safeQua?.classifyCertCode || mwrCerts?.classifyCertCode))
      }
    },
    noSafeScore() {
      const { safeQua } = this.userData;
      const { mainScore, projScore, classifyScore } = safeQua || {};
      return !mainScore && !projScore && !classifyScore;
    },
  },
  methods: {
    async initData() {
      this.loading = true;
      // 非个人申请
      if (this.bussType == 5 || this.bussType == 6) {
        this.$alert('请正确打开页面', '提示', {
          showClose: false,
          showConfirmButton: false,
          type: 'warning',
          center: true,
        });
        return false;
      }
      if (this.key) {
        // 登录
        const res = await userApi.loginWithToken({ token: this.key });
        const { token, sysAllDictItems, userInfo } = res;
        const decryptUserInfo = {
          ...userInfo,
          phone: userInfo.phone ? decrypt(userInfo.phone) : '',
          paperCode: userInfo.paperCode ? decrypt(userInfo.paperCode) : '',
        }
        this.$store.commit('dict/setDict', sysAllDictItems);
        this.$store.commit('user/setToken', token);
        this.$store.commit('user/setUserInfo', decryptUserInfo);
        // 判断用户类型，只接受个人用户进行申请
        if (userInfo.userType != 1) {
          this.$alert('本事项只接受个人用户申请，请退出后使用个人帐号登录', '提示', {
            showClose: false,
            showConfirmButton: false,
            type: 'warning',
            center: true,
          });
          return false;
        }
        // 获取用户信息（包括资质信息）
        await this.getUserData();
      } else {
        this.$alert('请正确打开页面', '提示', {
          showClose: false,
          showConfirmButton: false,
          type: 'warning',
          center: true,
        });
      }
      this.loading = false;
    },
    async getUserData() {
      if (this.certType == '3') {
        this.$alert('本事项只受理水利水电工程三类人员申请，请确认属于水利水电工程三类人员', '提示', {
          confirmButtonText: '确定',
          showClose: false,
          type: 'warning',
          center: true,
        });
      }
      let params = {
        id: this.$store.state.user.userInfo.id,
        type: this.certType,
      };
      const res = await userApi.getUserInfo(params);
      this.userData = {
        ...res,
        phone: res.phone ? decrypt(res.phone) : '',
        paperCode: res.paperCode ? decrypt(res.paperCode) : '',
      };
      // 查询是否已有未在系统内的证书
      await this.checkMwrCert();
      // 已有注册证书
      if (this.isReg) {
        if (this.hasAllCert) {
          this.$alert(`已有${this.certType == '1' ? '注册' : '合格'}证书`, '提示', {
            showClose: false,
            confirmButtonText: '确定',
            type: 'warning',
            center: true,
            callback: () => {
              this.$router.push({
                name: 'dockPersonalUserInfoQlf',
                params: {
                  certificate: 3,
                  disabled: true,
                },
              });
            },
          });
          return false;
        }
      }
      // 信息是否完整
      if (this.$store.state.user.userInfo.isCompleteInfo != 1) {
        this.$alert('请先完善个人信息', '提示', {
          confirmButtonText: '确定',
          showClose: false,
          type: 'warning',
          center: true,
          callback: () => {
            this.$router.push('/dockPersonalUserInfo');
          },
        });
        return false;
      }
      // 未找到安管知识考试成绩
      if (this.certType == '3' && this.noSafeScore) {
        this.$alert('请先填写安管知识考试成绩', '提示', {
          confirmButtonText: '确定',
          showClose: false,
          type: 'warning',
          center: true,
          callback: () => {
            this.$router.push({
              name: 'dockPersonalUserInfoQlf',
              params: {
                certificate: 3,
              },
            });
          },
        });
        return false;
      }
      // 未有注册证书、未进行初始注册
      if (!this.isReg && this.noCertCodes) {
        this.$alert(`请先进行${this.certType == '1' ? '初始注册' : '申领' }`, '提示', {
          showClose: false,
          showConfirmButton: false,
          type: 'warning',
          center: true,
        });
        return false;
      }
      this.checkStatus();
    },
    async checkStatus() {
      let params = {
        bussType: this.bussType,
        status: '0,1,3,9',
      };
      //查看是否有进行中的申请
      const { records } = await businessApi.getStepsList(params);
      if (records[0]) {
        let data = records[0];
        if (data.status == 0) {
          this.stepId = data.id;
          // status normal
          this.$refs.steps.init();
        } else if (data.status == 1 || data.status == 3) {
          this.$alert('当前申请正在受理审核中', '提示', {
            showClose: false,
            showConfirmButton: false,
            type: 'warning',
            center: true,
          });
          // 补齐补正
        } else if (data.status == 9) {
          this.$alert('当前申请需前往补正', '提示', {
            confirmButtonText: '确定',
            showClose: false,
            type: 'warning',
            center: true,
            callback: () => {
              this.$router.push({
                path: '/dockPersonalProcess',
                query: {
                  id: data.id,
                  bussType: this.bussType,
                  disabled: true,
                },
              });
            },
          });
        }
      }
    },
    async checkMwrCert() {
      const params = {
        holderCode: this.userData.paperCode
      }
      userApi.getCertInfoFromMwr(params).then(res => {
        if (res && res.status==200) {
          const { data } = res;
          const certList = data?.data;
          if (certList && certList.length) {
            this.$store.state.user.mwrCerts = certList;
            this.userData.mwrCerts = {}
            certList.forEach(cert => {
              const { CERT_NUM_CODE, TOP_PRO_LEVEL } = cert;
              if (TOP_PRO_LEVEL === 'A') {
                this.userData.mwrCerts.mainCertCode = CERT_NUM_CODE;
              }
              if (TOP_PRO_LEVEL === 'B') {
                this.userData.mwrCerts.projCertCode = CERT_NUM_CODE;
              }
              if (TOP_PRO_LEVEL === 'C') {
                this.userData.mwrCerts.classifyCertCode = CERT_NUM_CODE;
              }
            })
          }
        }
      })
    },
    // 加载中
    handleLoading(status) {
      this.loading = status;
    }
  },
};
</script>
<style lang="scss" scoped>
.personal-step {
  margin: 20px auto;
  width: 1620px;
}
</style>
